package com.achen.service;

import com.achen.pojo.Permission;
import com.achen.pojo.Role;
import com.achen.pojo.User;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 用户认证、权限管理
 * @author achen
 * @create 2020-04-24 1:25
 */
@Component //交给spring管理
public class SpringSecurityService implements UserDetailsService {
    //使用Dubbo通过网络远程调用服务提供方获取数据库中的用户信息
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        //根据用户名获取用户信息
        User user = userService.findByUsername(name);
        if(user == null){
            //用户不存在
            return null;
        }

        //将用户的角色和权限存放在list集合中
        List<GrantedAuthority> list = new ArrayList<>();
        //获取用户的角色,进行授权
        Set<Role> roles = user.getRoles();
        if(roles != null){
            //遍历角色
            for (Role role : roles) {
                //为用户授予角色
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                //获取用户对应的角色下对应的权限
                Set<Permission> permissions = role.getPermissions();
                if(permissions != null){
                    for (Permission permission : permissions) {
                        //为用户授权
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        //获取springsecurity的User用户
        org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(name,user.getPassword(),list); //密码已经加密
        return securityUser;
    }
}
